/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2024-01-30
 * Time: 11:39
 */
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
/*class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list = new LinkedList<>();
        preorder(root,list);
        return list;

    }
    public void preorder(TreeNode root, List<Integer> list) {
          if(root == null) {
            return;
        }
        list.add(root.val);
        preorder(root.left,list);
        preorder(root.right,list);
    }
}
*/

    //遍历思维
/*class Solution {
    List<Integer> list = new LinkedList<>(); //必须放在外面，里面的话，每次都会创建新的
    public List<Integer> preorderTraversal(TreeNode root) {
          if(root == null) {
            return list;
        }
        list.add(root.val);
        preorderTraversal(root.left);//这个并没有合理利用返回值
        preorderTraversal(root.right);
        return list;
    }
}*/
    //子问题思路
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list = new LinkedList<>();
        if(root == null) {
            return list;
        }
        list.add(root.val);
        List<Integer> leftTree = preorderTraversal(root.left);
        list.addAll(leftTree);
        List<Integer> rightTree = preorderTraversal(root.right);
        list.addAll(rightTree);
        return list;
    }
}
